package com.lzw.yin.controller;

import com.lzw.yin.constant.UserConstants;
import com.lzw.yin.domain.AjaxResult;
import com.lzw.yin.domain.entity.Role;
import com.lzw.yin.page.TableDataInfo;
import com.lzw.yin.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 角色管理
 */
@Controller
@RequestMapping(path = "/role")
public class RoleController extends BaseController {

    private IRoleService roleService;

    @Autowired
    public void setRoleService(IRoleService roleService) {
        this.roleService = roleService;
    }

    /**
     * 首页
     */
    @RequestMapping(path = {"/", "/index", ""}, method = RequestMethod.GET)
    public String role() {
        return "role/role";
    }

    /**
     * 新增角色
     */
    @GetMapping("/add")
    public String add() {
        return "role/add";
    }

    /**
     * 新增保存角色
     */
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated Role role) {
        if (UserConstants.ROLE_NAME_NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
            return error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        return toAjax(roleService.insertRole(role));

    }

    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Role role) {
        startPage();
        List<Role> list = roleService.selectRoleList(role);
        return getDataTable(list);
    }

    /**
     * 修改角色
     */
    @GetMapping("/edit/{roleId}")
    public String edit(@PathVariable("roleId") Long roleId, ModelMap map) {
        map.put("role", roleService.selectRoleById(roleId));
        return "role/edit";
    }

    /**
     * 修改保存角色
     */
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated Role role) {
        roleService.checkRoleAllowed(role);
        if (UserConstants.ROLE_NAME_NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
            return error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        return toAjax(roleService.updateRole(role));
    }

    /**
     * 角色状态修改
     */
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(Role role) {
        roleService.checkRoleAllowed(role);
        return toAjax(roleService.changeStatus(role));
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(roleService.deleteRoleByIds(ids));
    }

}
